
"""
    登陆日志
"""

from audit.serialiaers.landing import LanDingModelSerializer, LanDingModelExportSerializer
from audit.models import LanDingModel
from audit.views import operation
from utils.geoip2.geoip2 import geo
from utils.export import ExportExcel
from utils.json_response import JsonResponse
from utils.filter import DoctorsFilter
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from django_filters import rest_framework


class LanDingFilter(DoctorsFilter):
    """
    自定义搜索
    集成日期时间选择类
    """
    status = rest_framework.BooleanFilter(field_name='status')


class LanDingModelViewGet(ListModelMixin, GenericViewSet):
    """
    登陆日志：查导
    """
    perms_map = ({'*': 'admin'}, {'*': 'landing_all'}, {'get': 'landing_list'}, {'export': 'landing_export'})
    queryset = LanDingModel.objects.all()
    serializer_class = LanDingModelSerializer
    search_fields = ('username', 'name', 'agent', 'ip', 'city', 'why')  # 已在全局设置：指定字段模糊搜索
    filter_class = LanDingFilter
    ordering_fields = ('time',)

    sheet = '登陆日志'
    title = {
        'id': 'ID', 'username': '登陆用户', 'name': '用户名', 'tz': '时区', 'type': '类型', 'agent': '代理IP',
        'ip': 'IP地址', 'city': 'IP归属', 'why': '说明', 'status': '状态', 'time': '日期'
    }

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'export_current' or self.action == 'export_all':
            return LanDingModelExportSerializer
        return LanDingModelSerializer

    @action(methods=['post'], detail=False)  # url 访问127.0.0.1:8080/api/方法名
    def export_all(self, request):
        """
        根据数据表导出Excel表
        """
        serializer = self.get_serializer(self.queryset, many=True)
        name = ExportExcel(serializer.data, self.sheet, self.title).write(serializer.data, self.sheet, self.title)
        operation.operation(request, name, self.get_queryset().model._meta.verbose_name_plural, '导出所有')
        return JsonResponse(data={'name': name}, code=200, message='Excel 已导出')

    @action(methods=['post'], detail=False)  # url 访问127.0.0.1:8080/api/方法名
    def export_current(self, request):
        """
        根据前端传来的搜索内容、页码等条件导出Excel表
        """
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            name = ExportExcel(serializer.data, self.sheet, self.title).write(serializer.data, self.sheet, self.title)
            operation.operation(request, name, self.get_queryset().model._meta.verbose_name_plural, '导出部分')
            return JsonResponse(data={'name': name}, code=200, message='Excel 已导出')
        else:
            return JsonResponse(data={}, code=400, message='Excel 导出错误')


def landing(request, username, status, why):
    """
    记录登陆日志
    登陆接口调用
    """
    def_geo = '-'
    if status == 200:
        status = True
    else:
        status = False
    if 'HTTP_X_FORWARDED_FOR' in request.META:  # 获取ip
        client_ip = request.META['HTTP_X_FORWARDED_FOR']
        client_ip = client_ip.split(",")[0]  # 真实的ip
        def_geo = geo(client_ip)
    else:
        client_ip = '-'
    LanDingModel.objects.create(username=username, name='-', tz='-',
                                agent=request.META['REMOTE_ADDR'], type=request.META['HTTP_USER_AGENT'],
                                city=def_geo, ip=client_ip, why=why, status=status)
